package com.cbg.dg.controller;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.cbg.base.core.SuperEntity;
import com.cbg.base.utils.Result;
import com.cbg.bus.config.WXPayConfig;
import com.cbg.dg.entity.Passenger;
import com.cbg.dg.jwt.JwtUtils;
import com.cbg.dg.service.IPassengerService;
import com.cbg.discount.service.IDiscountRecordService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import com.cbg.base.core.SuperController;
import org.springframework.web.client.RestTemplate;
import java.util.Optional;

/**
 * <p>
 * 乘客表 前端控制器
 * </p>
 *
 * @author chenbing
 * @since 2018-12-20
 */
@RestController
@Api(value = "乘客控制器",tags = "乘客操作接口")
public class PassengerController extends SuperController<IPassengerService, Passenger> {
    @Autowired
    private RestTemplate restTemplate(){
        return new RestTemplate();
    }
    @Autowired
    StringRedisTemplate redisTemplate;
    @Autowired
    IPassengerService passengerService;
    private static final String GRANT_TYPE="authorization_code";
    @Autowired
    IDiscountRecordService discountRecordService;

    @ApiOperation(value="用户授权登录", notes="用户授权登录")
    @ApiImplicitParam(name = "code", value = "用户code随机码", required = true, dataType = "String", paramType = "query")
    @PostMapping("/login")
    public Result<?> login(String code){
        String code2Session="https://api.weixin.qq.com/sns/jscode2session?appid="+ WXPayConfig.appid +"&secret="+WXPayConfig.secret+"&js_code="+code+"&grant_type="+GRANT_TYPE;
        ResponseEntity<String> res= restTemplate().exchange(code2Session, HttpMethod.GET, null, String.class);
        String token=null;
        if(ObjectUtil.isNotNull(res)&&res.getStatusCode()== HttpStatus.OK){
            JSONObject jsonData = JSONUtil.parseObj(res.getBody());
            String openid = jsonData.get("openid", String.class);
            System.err.println("openid:"+openid);
            Passenger user = Optional.ofNullable(passengerService.getOne(new LambdaQueryWrapper<Passenger>()
                    .eq(Passenger::getOpenid, openid))).orElseGet(() ->{
                Passenger newUser = new Passenger().setOpenid(openid);
                newUser.insert();
                //首次登录 送优惠券
                discountRecordService.firstLogin(newUser.getId());
                return newUser;
            } );
            token = JwtUtils.sign(user.getId());
        }
        return Result.ok(token);
    }

    @ApiOperation(value="获取用户信息", notes="过滤部分敏感信息")
    @GetMapping("/user")
    public Result<?> user(){
        Passenger passenger = passengerService.getById(userId());
        passenger= (Passenger)passenger.setOpenid("******").setId("******");
        return Result.ok(passenger);
    }
}
